package com.triumphxx.readingreminderbackend.controller;

import com.triumphxx.readingreminderbackend.dto.ApiResponse;
import com.triumphxx.readingreminderbackend.dto.CompleteReviewRequest;
import com.triumphxx.readingreminderbackend.dto.NoteRequest;
import com.triumphxx.readingreminderbackend.entity.Note;
import com.triumphxx.readingreminderbackend.entity.ReviewSchedule;
import com.triumphxx.readingreminderbackend.service.NoteService;
import com.triumphxx.readingreminderbackend.service.ReminderService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:triumphxx
 * @Date: 2025/11/20
 * @Time: 17:16
 * @微信公众号：思考集结处
 * @网站：http://blog.triumphxx.com.cn
 * @GitHub https://github.com/triumphxx
 * @Desc: 笔记信息接口
 **/

@RestController
@RequestMapping("/api/notes")
@Validated
public class NoteController {

    @Autowired
    private NoteService noteService;

    @Autowired
    private ReminderService reminderService;

    // 获取所有笔记
    @GetMapping("getAll")
    public ApiResponse<List<Map<String, Object>>> getAllNotes() {
        List<Note> notes = noteService.getAllNotes();
        List<Map<String, Object>> response = new ArrayList<>();

        for (Note note : notes) {
            response.add(convertNoteToMap(note));
        }

        return ApiResponse.success(response);
    }

    // 根据ID获取笔记
    @GetMapping("/{id}")
    public ApiResponse<Map<String, Object>> getNoteById(@PathVariable Long id) {
        return noteService.findById(id)
                .map(note -> ApiResponse.success(convertNoteToMap(note)))
                .orElse(ApiResponse.error("笔记不存在"));
    }

    // 添加笔记
    @PostMapping("addOrUpdate")
    public ApiResponse<Map<String, Object>> addAndUpdateNote(@Valid @RequestBody NoteRequest request) {
        // 检查是否已存在相同语雀链接的笔记
//        if (noteService.findByYuqueUrl(request.getYuqueUrl()).isPresent()) {
//            return ApiResponse.error("该语雀笔记已存在");
//        }

        Note note = new Note();
        note.setId(request.getId());
        note.setTitle(request.getTitle());
        note.setYuqueUrl(request.getYuqueUrl());
        note.setContent(request.getContent());
        note.setFolder(request.getFolder());

        // 解析创建时间
        DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
        LocalDateTime createdAt = LocalDateTime.parse(request.getCreatedAt(), formatter);
        note.setCreatedAt(createdAt);

        Note savedNote = noteService.save(note);
        String message ="笔记添加成功";
        if (note.getId() != null){
            message ="笔记修改成功";
        }

        return ApiResponse.success(message, convertNoteToMap(savedNote));
    }

    // 获取今天需要复习的笔记
    @GetMapping("/today-reviews")
    public ApiResponse<Map<String, Object>> getTodayReviews() {
        List<Note> notes = noteService.getTodayReviews();

        List<Map<String, Object>> reviews = new ArrayList<>();
        for (Note note : notes) {
            for (ReviewSchedule schedule : note.getReviewSchedules()) {
                if (!schedule.getCompleted() && isToday(schedule.getScheduledDate())) {
                    Map<String, Object> review = new HashMap<>();
                    review.put("id", note.getId());
                    review.put("title", note.getTitle());
                    review.put("yuqueUrl", note.getYuqueUrl());
                    review.put("folder", note.getFolder());
                    review.put("createdAt", note.getCreatedAt());
                    review.put("stage", schedule.getStage());
                    review.put("scheduledDate", schedule.getScheduledDate());
                    reviews.add(review);
                }
            }
        }

        Map<String, Object> data = new HashMap<>();
        data.put("count", reviews.size());
        data.put("reviews", reviews);

        return ApiResponse.success(data);
    }

    // 标记复习完成
    @PatchMapping("/{id}/complete-review")
    public ApiResponse<String> completeReview(
            @PathVariable Long id,
            @Valid @RequestBody CompleteReviewRequest request) {

        boolean success = noteService.completeReview(id, request.getStage());

        if (success) {
            return ApiResponse.success("复习完成标记成功", null);
        } else {
            return ApiResponse.error("标记失败，笔记或复习阶段不存在");
        }
    }

    // 删除笔记
    @DeleteMapping("/{id}")
    public ApiResponse<String> deleteNote(@PathVariable Long id) {
        if (!noteService.findById(id).isPresent()) {
            return ApiResponse.error("笔记不存在");
        }

        noteService.delete(id);
        return ApiResponse.success("笔记删除成功", null);
    }

    /**
     * 前端主动 调用定时任务
     * @return
     */
    @GetMapping("/manual-trigger")
    public ApiResponse<String> manualTrigger() {
        reminderService.checkAndSendReminders();
        return ApiResponse.success("手动触发定时任务完成", null);
    }

    // 检查日期是否是今天
    private boolean isToday(LocalDateTime dateTime) {
        LocalDateTime today = LocalDateTime.now();
        return dateTime.toLocalDate().equals(today.toLocalDate());
    }

    // 工具方法：转换Note对象为Map
    private Map<String, Object> convertNoteToMap(Note note) {
        Map<String, Object> noteMap = new HashMap<>();
        noteMap.put("id", note.getId());
        noteMap.put("title", note.getTitle());
        noteMap.put("yuqueUrl", note.getYuqueUrl());
        noteMap.put("content", note.getContent());
        noteMap.put("createdAt", note.getCreatedAt());
        noteMap.put("folder", note.getFolder());
        noteMap.put("lastReminded", note.getLastReminded());
        noteMap.put("dbCreatedAt", note.getDbCreatedAt());
        noteMap.put("dbUpdatedAt", note.getDbUpdatedAt());

        List<Map<String, Object>> schedules = new ArrayList<>();
        if (note.getReviewSchedules() != null) {
            for (ReviewSchedule schedule : note.getReviewSchedules()) {
                Map<String, Object> scheduleMap = new HashMap<>();
                scheduleMap.put("id", schedule.getId());
                scheduleMap.put("stage", schedule.getStage());
                scheduleMap.put("scheduledDate", schedule.getScheduledDate());
                scheduleMap.put("completed", schedule.getCompleted());
                scheduleMap.put("completedAt", schedule.getCompletedAt());
                schedules.add(scheduleMap);
            }
        }
        noteMap.put("reviewSchedules", schedules);

        return noteMap;
    }
}